function ajax(url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.responseType = "json";
        xhr.onload = function () {
            if (this.status === 200) {
                resolve(this.response);
            } else {
                reject(this.statusText);
            }
        };
        xhr.send();
    });
}

function* main() {
    try {
        const users = yield ajax("/api/users.json");
        console.log("users", users);
        const posts = yield ajax("/api/posts.json");
        console.log("posts", posts);
        const urls = yield ajax("/api/urls.json");
        console.log("urls", urls);
    } catch (error) {
        console.log(error);
    }
}

function co(generator) {
    let g = generator();
    function handleResult(result) {
        // 生成器结束
        if (result.done) return;
        result.value
            .then((res) => {
                handleResult(g.next(res));
            })
            .catch((err) => {
                g.throw(new Error(err));
            });
    }
    handleResult(g.next());
}

co(main);
